import React, {useEffect, useState, useRef} from 'react';
import {useLocation} from '@umijs/max';
import {Form, Slider, DatePicker ,Space, Spin, message, TreeSelect, Button,Table, Tabs, Switch} from "antd";
import gcoord from 'gcoord'
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
import Map from '@/components/Map';
import {PageContainer} from '@ant-design/pro-components'
import {TableOutlined} from "@ant-design/icons";
import {vehicleTree, locationHistory} from '@/pages/monitor/historyTrack/service'
import {locationColumns} from './StreamInfo'
import {getCurrentDayDate} from '@/utils/TimeUtils'

import styles from './index.less'
const HistoryTrackMgr = (
  {
    
  }
) => {  
  const [form] = Form.useForm();
  const { RangePicker } = DatePicker;
  const dataSourceRef = useRef([]);
  const [dataSource, setDataSource] = useState(null);
  const [showTable, setShowTable] = useState(false);
  const [trackData, setTrackData] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [vehicleId, setVehicleId] = useState(useLocation().state?.state?.vehicleId);
  const [timeRange, setTimeRange] = useState(getCurrentDayDate().split(","));
  const [loading, setLoading] = useState(false);
  const [playText, setPlayText] = useState("播放");
  const [playVelocity, setPlayVelocity] = useState(1000);



  const startIcon = useRef(null);
  const endIcon = useRef(null);
  const carIcon = useRef(null);

  const map = useRef(null);
  const AMap = useRef(null);
  
  // const location = useLocation();
  // setVehicleId(location.state.state?.vehicleId)

  const onMapLoaded = (_map, _AMap) => {
    map.current = _map
    AMap.current = _AMap
    startIcon.current = new AMap.current.Icon({
      size: new AMap.current.Size(25, 34),
      image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
      imageSize: new AMap.current.Size(135, 40),
      imageOffset: new AMap.current.Pixel(-9, -3)
    });
    endIcon.current = new AMap.current.Icon({
      size: new AMap.current.Size(25, 34),
      image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
      imageSize: new AMap.current.Size(135, 40),
      imageOffset: new AMap.current.Pixel(-95, -3)
    });
    carIcon.current = new AMap.current.Icon({
      size: new AMap.current.Size(25, 34),
      image: '@/public/icons/map/ways-mark.png',
      imageSize: new AMap.current.Size(135, 40)
    });
  };

  const loadTreeData = () => {
    vehicleTree().then(res => {
      setTreeData(res?buildTreeData([res]):[]);
    });
  }

  const buildTreeData = (items) => {
    if (!items) {
      return []
    }
    return items.map((item, i) => {
      const result = {
        title: item.name,
        key: item.key,
        value: item.id,
        selectable: item.isLeaf,
        children: [],
      };
      result.parentCode = item.pid;
      result.children = buildTreeData(item.children);
      return result
    })
  }

  const queryTrack = () => {
    let params = {
      vehicleId: vehicleId,
      startTime: timeRange[0],
      endTime: timeRange[1]
    };
    setLoading(true)
    locationHistory(params).then(res => {
      if(res.items != null && res.items.length>0){
        setTrackData(res.items);
      }else{
        map.current.clearMap()
        message.warning("车辆在当前时间段无轨迹数据");
      }
    }).finally(setLoading(false));
  }
  const draw = () => {
    let path = [];
    if(trackData?.length == 0){
      return;
    }
    trackData.map((item, i) => {
      let lnglat = gcoord.transform([item.lng/1000000, item.lat/1000000], gcoord.WGS84, gcoord.GCJ02);
      path.push(
        new AMap.current.LngLat(lnglat[0], lnglat[1])
      );
    });
    
    var polyline = new AMap.current.Polyline({
      path: path,
      strokeWeight: 5, //线条宽度
      strokeColor: "red", //线条颜色
      lineJoin: "round", //折线拐点连接处样式
    });
    map.current.clearMap()
    map.current.add(polyline)
    map.current.setFitView();
    drawMarker(startIcon.current, path[0])
    drawMarker(endIcon.current, path[path.length - 1])
    
  }


  const drawMarker = (icon, point) => {
    const marker = new AMap.current.Marker({
      position: point,
      icon: icon,
      offset: new AMap.current.Pixel(-13, -30)
    });
    map.current.add(marker)
    return marker
  }

  const playIndex = useRef(0);
  const playState = useRef(false);
  const play = () => {
    if(playState.current){
      message.warning("当前正在播放中!")
      return;
    }
    if(trackData?.length > 0){
      _play()
      playState.current = true;
    }else{
      message.warning("车辆在当前时间段无轨迹数据")
    }
  }

  const waysMarkers = useRef([]);

  const resetPlayState = () => {
    playIndex.current = 0
    playState.current = false
  }
  const waysMarker = useRef(null);
  const _play = () => {
    playIndex.current = playIndex.current + 1;
    if(playIndex.current >= trackData.length){
      message.info("已回放完成!")
    }else{
      let item = trackData[playIndex.current]
      let lnglat = gcoord.transform([item.lng/1000000, item.lat/1000000], gcoord.WGS84, gcoord.GCJ02);
      if(!waysMarker.current){
        let marker = drawMarker(carIcon.current, new AMap.current.LngLat(lnglat[0], lnglat[1]))
        waysMarker.current = marker
      }else{
        waysMarker.current.setPosition(new AMap.current.LngLat(lnglat[0], lnglat[1]));

      }
      
      
      dataSourceRef.current.unshift(item)
      let tmpDataSource = [...dataSourceRef.current]
      setDataSource(tmpDataSource)
      console.log("速度: ", playVelocity)
      setTimeout(() => _play(), playVelocity)
    }
    
  }

  useEffect(() => {
    draw()
  }, [trackData]);


  useEffect(() => {
    loadTreeData()
  }, []);

  return (
    <PageContainer className={styles.pageContainer}>
      <Spin spinning={loading}>
      <div className={styles.container}>
        <div className={styles.topInfos}>
          <Form form={form}>
            <Space>
              <Form.Item
              label="车辆"
              name="vehicleId"
              rules={[
                {
                  required: true,
                  message: '请选择车辆',
                }, {type: 'string', max: 32}
              ]}
            >
              <TreeSelect 
                  treeData={treeData}
                  showSearch
                  treeDefaultExpandAll
                  listHeight={300}
                  defaultValue={vehicleId}
                  onSelect={setVehicleId}
                  style={{
                    width: '180px',
                  }}
              />          
            </Form.Item>

            <Form.Item
              label="时间范围"
              name="timeRange"
              rules={[
                {
                  required: true,
                  message: '请选择时间范围',
                }
              ]}
            >
              <RangePicker
                showTime={{
                  format: 'HH:mm',
                }}
                format="YYYY-MM-DD HH:mm"
                placeholder={['开始时间', '结束时间']}
                defaultValue={[dayjs(timeRange[0]), dayjs(timeRange[1])]}
                onChange={(value, dateString) => {
                  setTimeRange(dateString);
                }}
                disabledDate={
                  (current, { from }) => {
                    if (from) {
                      return Math.abs(current.diff(from, 'days')) >= 7;
                    }
                    return false;
                  }
                }
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={queryTrack}>查询</Button>
            </Form.Item>
          </Space>
        </Form>
        </div>

        {/**播放器 */}
        <div className={styles.player} style={{display: 'block'}}>
            <Form>
              <Form.Item
                label="播放速度"
                >
                  <Slider
                    min={1}
                    max={10}
                    defaultValue={5}
                    tooltip={{
                      open: true,
                    }}
                    onChange={(value) => {
                      let transValue = Math.abs(5 - value);
                      let transRate = transValue/2;
                      setPlayVelocity((5-value > 0) ? 1 + (transRate*1000) : 1 - (transRate*1000))
                    }}
                  />
              </Form.Item>
              <Form.Item
                label="地图跟随"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked/>
              </Form.Item>
              <Space>
                <Form.Item>
                  <Button type="primary" onClick={play}>播放</Button>
                </Form.Item>
                <Form.Item>
                  <Button type="primary">停止</Button>
                </Form.Item>
              </Space>
            </Form>
        </div>

        <div className={styles.mapWrap}>
          <Map onMapLoaded={onMapLoaded}></Map>
        </div>

        <div className={styles.bottomInfos} style={{display: showTable ? 'block' : 'none'}}>
          <Table 
            dataSource={dataSource} 
            columns={locationColumns} 
            size='small'
            scroll={
              {
              scrollToFirstRowOnChange:true,
              x:200,
              y:140,
            }
            }/>
        </div>
        <TableOutlined className={styles.tableSwitch} onClick={() => setShowTable(!showTable)}/>
      </div>


      
      </Spin>
    </PageContainer>
  );
}
export default HistoryTrackMgr;
